#!/usr/bin/perl

# Stop us from shooting outselves in the foot
use strict;
use warnings;
use FindBin qw($Bin);
use lib "$Bin";

# Our own helper package
use MDBUtils;
use MDBAWS;

# Local sub routines
sub process_file;

# Configuration
my $config = MDBUtils::get_config();
print "DEBUG: Read configuration file\n";

# Our variables..
my $metadata;
my $response;

$metadata->{'rcvd_DateTime'} = DateTime->now();
$metadata->{'rcvd_DateTime'}->set_time_zone("GMT");

my $filename = $ARGV[0];
process_file($filename);

exit;    # END OF PROGRAM

# Process the file
sub process_file($) {
    my $filename = shift
      or die("FUNCTION USAGE: process_file( filename );\n");

    print "DEBUG: process_file( " . $filename . " );\n";

    my $filetype = MDBUtils::filetype($filename);

    # What kind of content do we have?
    for ($filetype) {
        if (/Zip/) {
            my @filelist = MDBUtils::extract_archive_zip($filename);
            foreach my $file (@filelist) {
                process_file($file);
            }
        }
        elsif (/RAR/) {
            my @filelist = MDBUtils::extract_archive_rar($filename);
            foreach my $file (@filelist) {
                process_file($file);
            }
        }
        else {
            MDBAWS::store_sample( $filename, $metadata );
            unlink($filename);    # Remove the file after processing
        }
    }
}
